﻿using Mast.Common;
using Mast.DBUtility;
using Spring.Data.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mast.SpringDao
{
    public class DbProviderProxy
    {
        private string strDbType = string.Empty;
        private DatabaseType dbType;

        private static DbProviderProxy provider;

        public IDbProvider DbProvider { get; set; }

        public static DbProviderProxy Instance
        {
            get
            {
                if (provider == null)
                {
                    provider = new DbProviderProxy();
                }

                return provider;
            }

            set
            {
                provider = value;
            }
        }

        private DbProviderProxy()
        {

        }

        public void SetProvider(IDbProvider dbProvider)
        {
            provider.ConnectionString = dbProvider.ConnectionString;
            provider.DbType = GetDbType(dbProvider.DbMetadata.ProductName);
            DbProvider = dbProvider;
        }

        private DatabaseType GetDbType(string dbType)
        {
            dbType = dbType.ToLower();
            if (dbType.Contains("mysql"))
            {
                strDbType = "mysql";
                return DatabaseType.MYSQL;
            }
            else if (dbType.Contains("sqlserver"))
            {
                strDbType = "sqlserver";
                return DatabaseType.SQLSERVER;
            }
            else if (dbType.Contains("oledb"))
            {
                strDbType = "access";
                return DatabaseType.ACCESS;
            }
            else if (dbType.Contains("oracle"))
            {
                strDbType = "oracle";
                return DatabaseType.ORACLE;
            }
            else
            {
                throw new Exception("暂时不支持其它数据库类型");
            }
        }

        private string connectionString;

        public string ConnectionString 
        {
            get
            {
                if (!string.IsNullOrEmpty(connectionString)) return connectionString;
                return AdoHelper.GetConnectionString("connectionString");
            } 
            set
            {
                connectionString = value;
            }
        }

       

        public DatabaseType DbType {
            get
            {
                if (!string.IsNullOrEmpty(strDbType))
                {
                    return dbType;
                }
                else
                {
                    strDbType = CommonUtils.GetConfigValueByKey("dbType").ToUpper();
                    if (!string.IsNullOrEmpty(strDbType))
                    {
                        dbType = AdoHelper.DatabaseTypeEnumParse<DatabaseType>(strDbType);
                    }
                }

                return dbType;
            }
            set
            {
                dbType = value;
            }
        }
    }
}
